package com.framework.modules.job.task;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.framework.entity.sys.SysAgent;
import com.framework.entity.ter.TerMerchantReport;
import com.framework.entity.tran.TranTransactionInfo;
import com.framework.service.*;
import com.framework.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 考拉分润计算
 *
 * @author wq
 */
@Component("kaoLaBenefitTask")
public class KaoLaBenefitTask {


    @Autowired
    private TransactionInfoService transactionInfoService;

    @Autowired
    private AgentService agentService;

    @Autowired
    private AgentInfoService agentInfoService;

    @Autowired
    private BenefitDayService benefitDayService;

    @Autowired
    private TranTerBenefitDayService tranTerBenefitDayService;

    @Autowired
    private MerchantService merchantService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    private final BigDecimal MUTILPART = new BigDecimal("10000");

    /**
     * 考拉超收 。5的分润计算
     */
    public void dotFiveBenefit() {
        logger.info("------------考拉超收.5分润计算开始-----------------");
        //获取当前日期
        Date today = DateUtils.stringToDate(DateUtils.format(new Date()), DateUtils.DATE_PATTERN);
        Date benefitDate = DateUtils.addDateDays(today, -1);
        String benefitDateStr = DateUtils.format(benefitDate, DateUtils.DATE_PATTERN);

        List<TranTransactionInfo> list = transactionInfoService.selectList(new EntityWrapper<TranTransactionInfo>()
                .eq("transaction_date", benefitDateStr)
                .eq("is_benefited", 0)
                .eq("kaola_type", 2)
                .eq("dept_id", 889326)
                .eq("terminal_type", 1)
        );

        for (TranTransactionInfo info : list) {

            TerMerchantReport report = merchantService.queryMerchantBySn(info.getSn());
            if (report == null) {
                continue;
            }
            if (report.getAgentId().equals(66666L)) {
                continue;
            }
            SysAgent agent = agentService.queryAgentById(report.getAgentId());

            //一级合伙人或者盟主身份的都按照顶级计算
            if (agent.getPid().equals(66666L) || agent.getType().intValue() == 3) {
                topAgentBenefit(agent, info);
            } else {
                normalAgentBenefit(agent, info);
            }

        }
        logger.info("------------考拉超收.5分润计算结束-----------------");

    }


    private void topAgentBenefit(SysAgent agent, TranTransactionInfo info) {
        logger.info("------------考拉超收顶级盟主：-" + agent.getAgentId() + "计算分润----------------");
        BigDecimal topOwnerRate = new BigDecimal("2.8");

        BigDecimal amount = info.getAmount();

        BigDecimal topOwnBenefit = amount.multiply(topOwnerRate).divide(MUTILPART).setScale(2, BigDecimal.ROUND_HALF_UP);

        agentInfoService.addAmount(agent.getAgentId(), topOwnBenefit);

        benefitDayService.addSelfBenefitDay(info, topOwnBenefit, agent);

        tranTerBenefitDayService.addNewRecord(agent, info, topOwnBenefit);

        info.setIsBenefited(1);
        transactionInfoService.updateById(info);

        logger.info("------------考拉超收顶级盟主：-" + agent.getAgentId() + "计算分润----------------");


    }

    /**
     * 普通合伙人分润
     *
     * @param agent
     * @param info
     */
    private void normalAgentBenefit(SysAgent agent, TranTransactionInfo info) {
        logger.info("------------考拉超收普通用户：-" + agent.getAgentId() + "计算分润----------------");
        //给交易所属人计算万2的分润
        BigDecimal ownerRate = new BigDecimal("2");

        BigDecimal amount = info.getAmount();

        BigDecimal ownBenefit = amount.multiply(ownerRate).divide(MUTILPART).setScale(2, BigDecimal.ROUND_HALF_UP);

        agentInfoService.addAmount(agent.getAgentId(), ownBenefit);

        benefitDayService.addSelfBenefitDay(info, ownBenefit, agent);

        tranTerBenefitDayService.addNewRecord(agent, info, ownBenefit);
        //上级推荐人
        Long pid = agent.getPid();
        SysAgent baseAgent = agentService.queryBasicAgentBydeptId(889326L);
        //以递归方式查询最近的盟主，有则分润计算给他，无则分润计算给一级平台
        Long topAgentId = getTopAgent(agent.getPid(), baseAgent.getAgentId());
        SysAgent topAgent;
        //顶级推荐人
        if (topAgentId == null) {
            topAgent = agentService.queryTopAgentBySubIdAndBase(agent.getAgentId(), baseAgent.getAgentId());
        } else {
            topAgent = agentService.queryAgentById(topAgentId);
        }
        //如果上级和盟主同样
        if (pid.equals(topAgent.getAgentId())) {
            addTopAgentBenefit(topAgent, info);
        } else {
            addNormalBenfit(info, amount, ownBenefit, pid, topAgent);

        }

        info.setIsBenefited(1);
        transactionInfoService.updateById(info);

        logger.info("------------考拉超收普通用户：-" + agent.getAgentId() + "计算分润----------------");
    }

    private void addNormalBenfit(TranTransactionInfo info, BigDecimal amount, BigDecimal ownBenefit, Long pid, SysAgent topAgent) {
        //直属计算万0.5的分润
        BigDecimal pidRate = new BigDecimal("0.5");

        BigDecimal pidBenefit = amount.multiply(pidRate).divide(MUTILPART).setScale(2, BigDecimal.ROUND_HALF_UP);

        SysAgent pAgent = agentService.queryAgentById(pid);

        agentInfoService.addAmount(pid, pidBenefit);

        tranTerBenefitDayService.addNewRecord(pAgent, info, ownBenefit);

        benefitDayService.addTeamBenefit(info, pAgent, pidBenefit);

        //顶级计算0.3
        BigDecimal topRate = new BigDecimal("0.3");

        BigDecimal topBenefit = amount.multiply(topRate).divide(MUTILPART).setScale(2, BigDecimal.ROUND_HALF_UP);

        agentInfoService.addAmount(topAgent.getAgentId(), topBenefit);

        tranTerBenefitDayService.addNewRecord(topAgent, info, topBenefit);

        benefitDayService.addTeamBenefit(info, topAgent, topBenefit);

    }

    private Long getTopAgent(Long agentId, Long baseId) {
        SysAgent sysAgent = agentService.selectById(agentId);
        if (sysAgent.getAgentId().equals(baseId)) {
            return null;
        } else {
            //是盟主,则返回id
            if (sysAgent.getType().intValue() == 3) {
                return sysAgent.getAgentId();
                //非盟主,继续往上查
            } else {
                getTopAgent(sysAgent.getPid(), baseId);
            }
        }
        return null;
    }

    private void addTopAgentBenefit(SysAgent topAgent, TranTransactionInfo info) {

        //直属+顶级计算万0.5+0.3的分润
        BigDecimal pidRate = new BigDecimal("0.8");
        BigDecimal amount = info.getAmount();
        Long topAgentId = topAgent.getAgentId();
        BigDecimal benefit = amount.multiply(pidRate).divide(MUTILPART).setScale(2, BigDecimal.ROUND_HALF_UP);
        SysAgent pAgent = agentService.queryAgentById(topAgentId);

        agentInfoService.addAmount(topAgentId, benefit);

        tranTerBenefitDayService.addNewRecord(pAgent, info, benefit);

        benefitDayService.addTeamBenefit(info, pAgent, benefit);


    }


}
